package com.tommy.ddp.road
{
	import com.tommy.ddp.GridDataManager;
	import com.tommy.ddp.box.DdpBox;
	import com.tommy.ddp.definition.DDPConfig;
	import com.tommy.ddp.grid.DdpGrid;
	
	import flash.display.MovieClip;
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	
	import starling.events.Event;

	public class RoadWalker extends EventDispatcher
	{
		public static const FINISH:String = "finish";
		
		private var _path:Vector.<Point>;
		private var _box:DdpBox;
		private var grid:DdpGrid;
		private var point:Point;
		private var isWalking:Boolean;
		private var _index:uint;
		
		private var targetX:int;
		private var targetY:int;
		
		
		public function RoadWalker()
		{
		}
		public function walk(b:DdpBox,path:Vector.<Point>):void
		{
			_index = 0;
			_box = b;
			_path = path;
			if(path.length == 0)
			{
				dispatchEvent(new flash.events.Event(FINISH));
				return;
			}
			
			GridDataManager.removeBox(_box);
			
			_box.addEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		public function dispose():void
		{
			if(_box)
			{
				_box.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
			}
			_path = null;
			_box = null;
			grid = null;
			point = null;
		}
		
		private function onEnterFrame(event:Event):void
		{
			if(_index == _path.length)
			{
				_box.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
				if(grid)
				{
					grid.isMoving = false;
					grid.isOccupied = false;
				}
				var p2:Point = _path[_path.length - 1];
				_box.column = p2.x;
				_box.row = p2.y;
				GridDataManager.regBox(p2.x,p2.y,_box);
				
				dispatchEvent(new flash.events.Event(FINISH));
				return;
			}
			
			var p:Point = _path[_index];
			if(point == p)
			{
				move(p);
				return;
			}
			var g:DdpGrid = GridDataManager.getGrid(p.x,p.y);
			if(g && g.isMoving)
				return;
			//要走新的格子了，新之前的状态清掉
			if(grid)
				grid.isMoving = false;
			
			point = p;
			grid = g;
			if(grid)
				grid.isMoving = true;
			
			move(p);
		}
		
		private function move(p:Point):void
		{
			targetX = p.x*DDPConfig.GRID_SIZE_W;
			targetY = p.y*DDPConfig.GRID_SIZE_H;
			
			var dir:int = targetX < _box.x ? -1: 1;
			
			if(Math.abs(targetX - _box.x) < DDPConfig.MOVE_ROW_SPEED)
			{
				_box.x = targetX;
			}
			else
				_box.x += DDPConfig.MOVE_ROW_SPEED*dir;
			
			if(_box.y >= targetY)
			{
				_box.y = targetY;
			}
			else
				_box.y += DDPConfig.MOVE_ROW_SPEED;
			
			if(_box.x >= targetX && _box.y >= targetY)
			{
				_box.x = targetX;
				_box.y = targetY;
				_index++;
			}
		}
	}
}

//|||
/*
行走过程中如果发现前方有棋子挡住了但是还让我走，和那个棋子交换目标点

*/


